package com.learning.rocketmq.producer;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;

/**
 * ClassName: SimpleAsyncProducer
 * Description: 简单异步 Producer
 * Date: 2018/12/26 14:04 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class SimpleAsyncProducer {
    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException, MQBrokerException {

        // 1- 设置 GroupName
        DefaultMQProducer producer = new DefaultMQProducer("base_producer_group");
        // 设置NameServer 地址
        producer.setNamesrvAddr("10.0.64.106:9876;10.0.64.107:9876");
        // 设置 lnstanceName ，当一个Jvm 需要启动多个Producer 的时候，通过 设置不同的InstanceName 来区分，不设置的话系统使用默认名称“DEFAULT” 。
        producer.setInstanceName("base_producer");
        // 设置发送失败重试次数
        producer.setRetryTimesWhenSendFailed(3);
        producer.start();

        // 组装消息并发送
        // 消息的发送有同步和异步两种方式
        for (int i = 0; i < 100; i++) {
            Message message = new Message("base_topic", "base_api", ("Hello RocketMQ > " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));

            // 异步发送
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.printf("%s%n", sendResult);
                    sendResult.getSendStatus();
                }

                @Override
                public void onException(Throwable e) {
                    e.printStackTrace();
                }
            });
        }

        producer.shutdown();

    }
}
